<?php

namespace App\Http\Controllers\Api\Operate;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Goods\GoodsLogic;
use App\Libs\Strategy\Context;
use Flaravel\Upload\Fupload;
use App\Models\Operate\Banners;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    private $banner;

    public function __construct()
    {
        $this->banner = new Context(new Banners());
    }

    public function index()
    {
        $banners = $this->banner->display(10);
        return $this->success($banners);
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'sort' => 'integer|max:65536'
        ],[
            'sort.max' => '排序超出最大值:65535'
        ]);
        $this->validate($request,['img'=>'required|url']);
        if($res = $this->banner->create($request->only('img','type','sort')));
        {
              return $this->success(['message'=>'添加成功']);
        };
        return $this->error('添加失败');
    }

    public function update(Request $request,$id)
    {
        $this->validate($request,[
            'sort' => 'integer|max:65536'
        ],[
            'sort.max' => '排序超出最大值:65535'
        ]);
        if($this->banner->update($id,$request->only('img','type','sort')));
        {
              return $this->success(['message'=>'更新成功']);
        };
        return $this->error('更新失败');
    }


    public function destroy($id)
    {
        $banner = $this->banner->find($id);
        if(!empty($banner->img))
        {
            Fupload::delete($banner->img);
        }
        if($banner->delete($id))
        {
            return $this->success(['message'=>'删除成功']);
        }
        return $this->error('删除失败');
    }
}
